package com.weasel.weixin.mp.jetty;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.SessionManager;
import org.eclipse.jetty.server.session.HashSessionIdManager;
import org.eclipse.jetty.server.session.HashSessionManager;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import javax.servlet.Servlet;

/**
 * Created by Dylan on 2015/9/28.
 */
public final class JettyServletLauncher {

    private Server server = null;

    /**
     * @param port
     * @return
     */
    public static JettyServletLauncher listen(int port){

        JettyServletLauncher launcher = new JettyServletLauncher();
        launcher.server = new Server(port);

        HashSessionIdManager hashSessionIdManager = new HashSessionIdManager();
        SessionManager sessionManager = new HashSessionManager();
        sessionManager.setSessionIdManager(hashSessionIdManager);
        SessionHandler sessionHandler = new SessionHandler();
        sessionHandler.setSessionManager(sessionManager);

        ServletHandler servletHandler = new ServletHandler();
        servletHandler.setHandler(sessionHandler);

        launcher.server.setHandler(servletHandler);
        launcher.server.setSessionIdManager(hashSessionIdManager);
        return launcher;
    }

    /**
     * @param servlet
     * @param path
     * @return
     */
    public JettyServletLauncher addServletWithMapping(Servlet servlet,String path){

        ((ServletHandler)this.server.getHandler()).addServletWithMapping(new ServletHolder(servlet), path);
        return this;
    }

    public JettyServletLauncher addFilterWithMapping(java.lang.Class filter,String path){
        ((ServletHandler)this.server.getHandler()).addFilterWithMapping(filter,path, 15);
        return this;
    }

    /**
     *
     */
    public void launch(){
        try {
            this.server.start();
            this.server.join();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private JettyServletLauncher(){}

}
